package com.eckey.lab.service.impl;

import com.alibaba.fastjson.JSON;
import com.eckey.lab.entity.Order;
import com.eckey.lab.dao.OrderDao;
import com.eckey.lab.feign.StorageFeign;
import com.eckey.lab.feign.UserFeign;
import com.eckey.lab.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * (Order)表服务实现类
 *
 * @author makejava
 * @since 2023-09-11 15:49:09
 */
@Slf4j
@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderDao;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private StorageFeign storageFeign;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    public Order queryById(Integer id) {
        return this.orderDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param order 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
/*
    @Override
    public Page<Order> queryByPage(Order order, PageRequest pageRequest) {
        long total = this.orderDao.count(order);
        return new PageImpl<>(this.orderDao.queryAllByLimit(order, pageRequest), pageRequest, total);
    }
*/

    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @GlobalTransactional
    public Order insert(Order order) {
        try {
            order.setCreateDate(new Date());
            order.setModifyDate(new Date());
            log.info("add order:{}", JSON.toJSONString(order));
            this.orderDao.insert(order);
            //扣用户余额
            userFeign.deduct(order.getUserId(), order.getTotalPrice());

            //扣库存
            storageFeign.deduct(order.getName(), order.getProductNum());

        } catch (Exception e) {
            log.error("下单异常：{}", e);
            throw new RuntimeException(e);
        }
        return order;
    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    public Order update(Order order) {
        this.orderDao.update(order);
        return this.queryById(order.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    public boolean deleteById(Integer id) {
        return this.orderDao.deleteById(id) > 0;
    }
}
